/**
 * zmn渠道管理-列表
 * 文件命名格式：zmn.模块名称.表名称.功能.js
 * @author xiangjunming
 * @since 2019/08/22 18:07
 */
layui.define(['index', 'form', 'table', 'laypage', 'layedit', 'laydate', 'formSelects', 'tooltipster', 'laytpl', 'zmnSelect'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    var table = layui.table;
    var laypage = layui.laypage;
    let zmnSelect = layui.zmnSelect;
    var layedit = layui.layedit;
    var laydate = layui.laydate;
    let formSelects = layui.formSelects;
    var tooltipster = layui.tooltipster;
    var laytpl = layui.laytpl;

    var data = {"code": 0, "msg": "", "count": json.totalCount};

    table.init('zmn-table', {
        toolbar: "#zmn-table-tool",
        page: true,
        limit: json.pageSize,
        // json.hasExportExcel ? ['exports', 'filter'] : ['filter']
        defaultToolbar: ['filter'], done: function () {
            $("div[lay-event='LAYTABLE_EXPORT']").attr('lay-event', 'CUSTOM_EXPORT');
        },
        height: 'full-280'
    });
    laypage.render(zmnPage.laypageOptions(json));

    // 修改排序
    table.on("edit(zmn-table)", function (obj) {
        zmnPage.laySort(obj, "/channel/updateSort.action", obj.data.channelId);
    });

    // 启用/停用（批量）
    table.on("toolbar(zmn-table)", function (obj) {
        var ids = zmnPage.layTabldIds(obj, "channelId");
        if(obj.event == "start" || obj.event == "stop") {
            if (ids.length === 0) {
                return layer.alert("请选择至少一个渠道！");
            }
            zmnPage.layStartStopBatch(obj, "/channel/modifyStatus", ids.join(","));
        }
        switch (obj.event) {
            case 'CUSTOM_EXPORT':
                // $("#query-export").click();
        }
    });

    form.on('submit(query-export)', function (data) {
        var params = Object.keys(data.field).map(function (key) {
            // body...
            return encodeURIComponent(key) + "=" + encodeURIComponent(data.field[key]);
        }).join("&");
        var url = "/channel/exportExcel.action?" + params;
        window.open(url, "_parent");
        return false;
    });

    zmnSelect.selectOrganizeDeptTree('deptId',{
        selectedValues:[json.obj.deptId == null ? '' : json.obj.deptId],//回显值，格式：数组[depId1,depId2]
        remote: { //远程获取下拉数据
            enable: true, //开关：true-开启；false-关闭
            url: json.SYS_MCC + '/common/dept/listDeptTree.action?orgId=' + 0, //服务url
        },
        events: {
            /**
             * 选择中事件
             * @param values 已选中值，Array类型
             */
            changing: function (values) {
                console.log("----------------------正选中的值:" + values);
            }
        }
    });

    zmnSelect.selectOrganizeDeptTree('abutmentDeptId',{
        selectedValues:[json.obj.abutmentDeptId == null ? '' : json.obj.abutmentDeptId],//回显值，格式：数组[depId1,depId2]
        remote: { //远程获取下拉数据
            enable: true, //开关：true-开启；false-关闭
            url: json.SYS_MCC + '/common/dept/listDeptTree.action?orgId=' + 0, //服务url
        },
        events: {
            /**
             * 选择中事件
             * @param values 已选中值，Array类型
             */
            changing: function (values) {
                console.log("----------------------正选中的值:" + values);
            }
        }
    });

    // 省市联动
    form.on('select(provinceId)', function(obj){
        triggerCityOptions(obj.value);
    })

    // 平台所属组织下1级部门联动
    form.on('select(plat)', function(obj){
        triggerOneDeptOptions(obj.value);
        triggerOneChannelOptions(obj.value);
    })

    // 2级部门联动
    form.on('select(oneDeptId)', function(obj){
        triggerTwoDeptOptions(obj.value);
        var plat = $("#plat").find("option:selected").val();
        triggerOneChannelOptions(plat, obj.value);
    })

    // 3级部门联动
    form.on('select(deptId)', function(obj){
        var plat = $("#plat").find("option:selected").val();
        var oneDeptId = $("#oneDeptId").find("option:selected").val();
        triggerOneChannelOptions(plat, oneDeptId, obj.value);
    })

    // 故障价格表联动
    form.on('select(bizType)', function(obj){
        triggerTariffOptions(obj.value);
    })

    form.on('select(servBizType)', function(obj){
        triggerServPriceTableOptions(obj.value);
    })

    function triggerCityOptions(value){
        let cityOptions = json.citys.filter(p => p.parentId == value).map(p => {
            return p.areaId == json.cityId ? '<option value="'+p.areaId+'" selected="selected">'+p.name+'</option>' : '<option value="'+p.areaId+'">'+p.name+'</option>';
        });
        cityOptions.unshift('<option value=""></option>');
        $('#cityId').html(cityOptions);
        form.render("select");
    }

    function triggerOneDeptOptions(value){
        let oneDeptOptions = json.oneDepts.filter(p => p.orgId == value).map(p => {
            return p.deptId == json.obj.oneDeptId ? '<option value="'+p.deptId+'" selected="selected">'+p.deptName+'</option>' : '<option value="'+p.deptId+'">'+p.deptName+'</option>';
        });
        oneDeptOptions.unshift('<option value=""></option>');
        $('#oneDeptId').html(oneDeptOptions);
        form.render("select");
    }

    function triggerTwoDeptOptions(value){
        let twoDeptOptions = json.twoDepts.filter(p => p.parentId == value).map(p => {
            return p.deptId == json.obj.deptId ? '<option value="'+p.deptId+'" selected="selected">'+p.deptName+'</option>' : '<option value="'+p.deptId+'">'+p.deptName+'</option>';
        });
        twoDeptOptions.unshift('<option value=""></option>');
        $('#deptId').html(twoDeptOptions);
        form.render("select");
    }

    function triggerOneChannelOptions(plat, oneDeptId, deptId){
        oneDeptId = zmnUtil.isEmptyNull(oneDeptId) ? null : oneDeptId;
        deptId = zmnUtil.isEmptyNull(deptId) ? null : deptId;
        let oneChannelOptions = json.oneChannels.filter(p => (plat == null || p.plat == plat) && (oneDeptId == null || p.oneDeptId == oneDeptId) && (deptId == null || p.deptId == deptId)).map(p => {
            return p.channelId == json.obj.parentId ? '<option value="'+p.channelId+'" selected="selected">'+p.name+'</option>' : '<option value="'+p.channelId+'">'+p.name+'</option>';
        });
        oneChannelOptions.unshift('<option value=""></option>');
        $('#parentId').html(oneChannelOptions);
        form.render("select");
    }

    function triggerTariffOptions(value){
        let faultTariffOptions = json.faultTariffs.filter(p => (p.bizType == value && p.tariffType == 2)).map(p => {
            return p.tariffId == json.obj.tariffId ? '<option value="'+p.tariffId+'" selected="selected">'+p.tariffName+'</option>' : '<option value="'+p.tariffId+'">'+p.tariffName+'</option>';
        });
        faultTariffOptions.unshift('<option value=""></option>');
        $('#tariffId').html(faultTariffOptions);
        form.render("select");
    }

    function triggerServPriceTableOptions(value){
        let faultTariffOptions = json.faultTariffs.filter(p => (p.bizType == value && p.tariffType == 1)).map(p => {
            return p.tariffId == json.obj.tariffId ? '<option value="'+p.tariffId+'" selected="selected">'+p.tariffName+'</option>' : '<option value="'+p.tariffId+'">'+p.tariffName+'</option>';
        });
        faultTariffOptions.unshift('<option value=""></option>');
        $('#servPriceId').html(faultTariffOptions);
        form.render("select");
    }

    if(json.provinceId){
        console.log('triggerCityOptions')
        triggerCityOptions(json.provinceId);
    }
    if(json.obj.oneDeptId){
        console.log('triggerTwoDeptOptions')
        triggerTwoDeptOptions(json.obj.oneDeptId);
    }
    if(json.obj.plat){
        console.log('triggerOneChannelOptions')
        triggerOneChannelOptions(json.obj.plat, json.obj.oneDeptId, json.obj.deptId);
        triggerOneDeptOptions(json.obj.plat);
    }
    if(json.obj.tariffId){
        console.log('triggerTariffOptions')
        triggerTariffOptions(json.obj.bizType);
    }
    if(json.obj.servPriceId){
        console.log('triggerServPriceTableOptions')
        triggerServPriceTableOptions(json.obj.bizType);
    }

    form.on("switch(chk_status)", function (obj) {
        console.log(obj);
        let  url = "/channel/modifyStatus.action";
        let channelId = obj.elem.getAttribute("key");
        let status = obj.elem.checked ? 2 : 1;
        console.log(status);
        switch (status) {
            case 1:
                zmnPage.ajaxSimple(url, {ids: channelId, status: 1}, 1000);
                break;
            case 2:

                zmnPage.ajaxSimple(url, {ids: channelId, status: 2}, 1000);
                break;
        }
        setTimeout(function () {
            location.reload(true);
        }, 3000);
    });

    // 提交
    form.on('submit(zmn-form-submit)', function(obj){
        var data = obj.field;
        var url = "/channel/configInnerName.action";
        $.ajax({
            async: false,
            type: "POST", url: url,
            dataType: "json", data: data,
            success:function(resp) {
                var message = resp.status == 200 ? "操作成功！" : resp.message;
                layer.msg(message);
                // if(resp.status == 200) {
                //     zmnPage.reload(resp.message, 1000);
                // }
            },
            error:function(XMLHttpRequest, status, errorThrown){}
        });
        return false;
    });

    var channelId,obj;
    $("body").on("mouseover", ".btn-operate", event => {
        channelId = $(event.target).data("id");
        let index = $(event.target).data("index");
        obj = layui.table.cache["zmn-table"][index];
    });

    function operatorFun() {
        var tooltipsterData = [];
        if(json.hasViewEdit){
            tooltipsterData.push({text: '详情', id: 1});
        }
        if(json.hasViewSettle){
            tooltipsterData.push({text: '结算', id: 2});
        }
        if(json.hasViewOutPrice){
            tooltipsterData.push({text: 'C-保外价格', id: 3});
        }
        if(json.hasViewInPrice){
            tooltipsterData.push({text: 'F-保内价格', id: 4});
        }
        if(json.hasViewProjectPrice){
            tooltipsterData.push({text: 'B-工程价格', id: 5});
        }
        if(json.hasViewConfigInnerName){
            tooltipsterData.push({text: '配置内部名称', id: 6});
        }
        // 表格操作按钮
        tooltipster.createOperateCard({
            el: '.btn-operate',
            maxWidth: 270,
            data: tooltipsterData,
            onClick: function (dataObj) {
                var title = dataObj.data.text;
                var tabIndex = dataObj.data.id;
                if (tabIndex === 1) {
                    // zmnLayUtil.openTabsPageCustom(parent, `/channel/detail.action?channelId=${channelId}`, title);
                    parent.layui.index.openTabsPage(`/channel/detail.action?channelId=${channelId}`, title);
                    return false;
                }
                if (tabIndex === 2) {
                    // zmnLayUtil.openTabsPageCustom(parent, `/channel/settle.action?channelId=${channelId}`, title);
                    parent.layui.index.openTabsPage(`/channel/settle.action?channelId=${channelId}`, title);
                    return false;
                }
                if (tabIndex === 3) {
                    // zmnLayUtil.openTabsPageCustom(parent, `/channel/priceList.action?channelId=${channelId}&bizType=1`, title);
                    parent.layui.index.openTabsPage(`/channel/priceList.action?channelId=${channelId}&bizType=1`, title);
                    return false;
                }
                if (tabIndex === 4) {
                    // zmnLayUtil.openTabsPageCustom(parent, `/channel/priceList.action?channelId=${channelId}&bizType=2`, title);
                    parent.layui.index.openTabsPage(`/channel/priceList.action?channelId=${channelId}&bizType=2`, title);
                    return false;
                }
                if (tabIndex === 5) {
                    // zmnLayUtil.openTabsPageCustom(parent, `/channel/priceList.action?channelId=${channelId}&bizType=3`, title);
                    parent.layui.index.openTabsPage(`/channel/priceList.action?channelId=${channelId}&bizType=3`, title);
                    return false;
                }
                if (tabIndex === 6) {
                    let obj2 = {channelId: obj.channelId, name: obj.name, innerName: obj.innerName ? obj.innerName : ''}
                    laytpl(configInnerNameHtml.innerHTML).render(obj2, function(html) {
                        childIndex = layer.open({
                            type: 1,
                            title: '配置内部名称'
                            ,content: html
                            , area: ['400px', '250px']
                        });
                    });
                    return false;
                }
            }
        });
    }

    operatorFun();

    //对外暴露的接口
    exports('channel_list', {});
});